package com.std.getstuffdone;

/**
 * This class handles the Schedule Screen UI and controls
 * @author Team STD
 *
 */
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;

import models.DataSource;
import models.DbHelper;
import models.Task;
import models.Utility;

import com.std.getstuffdone.R;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.format.Time;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class PreviewScheduleScreenActivity extends ListActivity implements OnClickListener{
	
	// constant string values
    private final String STARTTIMELABEL = "Start Time: ";
    private final String DURATIONLABEL = "Duration: ";
    private final String PRIORITYLABEL = "Priority: ";
    
    private Collection<Task> tasksToDisplay;
    static  ArrayList<HashMap<String,String>> list;
    private DataSource dataSource;
    
    // this method is called every time the preview screen is displayed
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.previewschedulescreenactivity);
		
		// a singleton database utitility that has database methods
		dataSource = DataSource.getInstance(getApplicationContext());
        
		// prepare buttons
		Button SaveButton = (Button)findViewById(R.id.SavePreview);
		SaveButton.setOnClickListener(this);
		Button DiscardButton = (Button)findViewById(R.id.discardPreview);
		DiscardButton.setOnClickListener(this);
		
		// show generated schedule tasks
		displayScheduleTasks();
		
		// prepare displayed list view
		ListView lv = getListView();
        lv.setTextFilterEnabled(true);
       
        // if some tasks are dropped from the generated schedule, then show this dialog
        if(!Utility.getAllTasksIncludedFlag()) {
        	displayNotAllTasksIncludedDialog();
        }
	}
	
	// dialog to be displayed when not all tasks are included in the new schedule
	private void displayNotAllTasksIncludedDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Generated Schedule Alert");

		// build message depending on all tasks included flag
		builder.setMessage("Not all tasks were included in the generated schedule.");
		builder.setInverseBackgroundForced(true);
		builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		AlertDialog alert = builder.create();
		alert.show();
	}

	// show tasks scheduled
	private void displayScheduleTasks() {
        // set the adapter information to display data
        list = new ArrayList<HashMap<String,String>>();
        SimpleAdapter adapter = new SimpleAdapter(this,list,R.layout.preview_list_item,
                        new String[] {"title","startTime","duration","priority"},
                        new int[] {R.id.title,R.id.startTime, R.id.duration, R.id.priority}
        );
        dataSource.open();
        tasksToDisplay = dataSource.getAllTasks(DbHelper.TABLE_PREVIEW);
        dataSource.close();
        populateList(tasksToDisplay);
        setListAdapter(adapter);
	}

	// populates list with data to display from a list of tasks
    // @param tasks A list of tasks to be displayed on screen
    private void populateList(Collection<Task> tasks) {
        for(Task t : tasks) {
                HashMap<String,String> temp = new HashMap<String,String>();
                temp.put("title", t.getTitle());
                temp.put("startTime", STARTTIMELABEL + parseTime(t.getStartTime()));
                temp.put("duration", DURATIONLABEL + t.getEstimatedDuration() + " min");
                temp.put("priority", PRIORITYLABEL + Utility.getPriorityString(t.getPriority()));
                list.add(temp);
        }
    }
   
    // parses Time object to display in HH:MM string format
    // @param time Time object to display
    // @return String with time in HH:MM format. 'Time not set' if time is null
    private String parseTime(Time time) {
        if (time == null) {
                return "Not Set";
        }
        if(time.toString().substring(6,8).equals("13")) {
        	return time.toString().substring(9, 11) + ":" + time.toString().substring(11,13) + " [+1 Day]";
        }
        return time.toString().substring(9, 11) + ":" + time.toString().substring(11,13);
    }
	
    // switches between planning and schedule activities
    public void switchTabInActivity(int indexTabToSwitchTo){
    	TabWidget ParentActivity;
    	ParentActivity = (TabWidget) this.getParent();
    	ParentActivity.switchTab(indexTabToSwitchTo);
	}
    
    public void onClick(View v) {
    	int viewId = v.getId();
    	Intent intent = new Intent();
    	if(viewId == R.id.SavePreview){
    		setResult(Utility.RETURN_CODE_SAVE_PREVIEW, intent);
    		finish();
    	}
    	else if (viewId == R.id.discardPreview) {
    		displayAlertDialog();
    	}
    }
	 
	// displays an alert dialog to user to indicate invalid input
	private void displayAlertDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Confirmation");
				
		builder.setMessage("Confirm Discard Schedule");
		builder.setInverseBackgroundForced(true);
		builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			
			public void onClick(DialogInterface dialog, int which) {
								
				dialog.dismiss();
			}
		});
		
		builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
					
			public void onClick(DialogInterface dialog, int which) {
				Intent intent = new Intent();
				setResult(Utility.RETURN_CODE_CANCEL, intent);				
				dialog.dismiss();
				finish();
			}
		});
		AlertDialog alert = builder.create();
		alert.show();
							
	}
}

